#Boa:Frame:Frame1

import wx
import os
import traceback
import time
import VideoCapture
import datetime
import shutil 
from PIL import Image, ImageEnhance, ImageDraw, ImageFont, ImageFilter


def create(parent):
    return Frame1(parent)

[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1BUTTON3, 
 wxID_FRAME1PANEL1, wxID_FRAME1STATICBITMAP1, wxID_FRAME1STATICBITMAP2, 
 wxID_FRAME1STATICTEXT1, wxID_FRAME1STATICTEXT2, wxID_FRAME1STATICTEXT3, 
 wxID_FRAME1STATICTEXT4, wxID_FRAME1STATICTEXT5, wxID_FRAME1TEXTCTRL1, 
 wxID_FRAME1TEXTCTRL2, wxID_FRAME1TEXTCTRL3, 
] = [wx.NewId() for _init_ctrls in range(15)]

[wxID_FRAME1TIMER1, wxID_FRAME1TIMER2] = [wx.NewId() for _init_utils in range(2)]

class Frame1(wx.Frame):
    def _init_utils(self):
        # generated method, don't edit
        self.timer1 = wx.Timer(id=wxID_FRAME1TIMER1, owner=self)
        self.timer2 = wx.Timer(id=wxID_FRAME1TIMER2, owner=self)
        self.Bind(wx.EVT_TIMER, self.OnTimer1Timer, id=wxID_FRAME1TIMER1)
        self.Bind(wx.EVT_TIMER, self.OnTimer2Timer, id=wxID_FRAME1TIMER2)

    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
              pos=wx.Point(163, 145), size=wx.Size(1049, 459),
              style=wx.DEFAULT_FRAME_STYLE,
              title='\xcc\xf5\xc2\xeb\xca\xb6\xb1\xf0\xcd\xbc\xcf\xf1\xb2\xb6\xd7\xbd\xd6\xfa\xca\xd6')
        self._init_utils()
        self.SetClientSize(wx.Size(1033, 421))

        self.panel1 = wx.Panel(id=wxID_FRAME1PANEL1, name='panel1', parent=self,
              pos=wx.Point(0, 0), size=wx.Size(1033, 421),
              style=wx.TAB_TRAVERSAL)

        self.staticBitmap1 = wx.StaticBitmap(bitmap=wx.NullBitmap,
              id=wxID_FRAME1STATICBITMAP1, name='staticBitmap1',
              parent=self.panel1, pos=wx.Point(19, 59), size=wx.Size(400, 300),
              style=0)

        self.staticBitmap2 = wx.StaticBitmap(bitmap=wx.NullBitmap,
              id=wxID_FRAME1STATICBITMAP2, name='staticBitmap2',
              parent=self.panel1, pos=wx.Point(441, 59), size=wx.Size(400, 300),
              style=0)

        self.textCtrl1 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL1, name='textCtrl1',
              parent=self.panel1, pos=wx.Point(262, 379), size=wx.Size(145, 22),
              style=wx.TE_MULTILINE, value='')
        self.textCtrl1.Bind(wx.EVT_TEXT_ENTER, self.OnTextCtrl1TextEnter,
              id=wxID_FRAME1TEXTCTRL1)

        self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
              label='\xca\xe4\xc8\xeb\xcc\xf5\xc2\xeb(\xbb\xd8\xb3\xb5\xc8\xb7\xc8\xcf)\xa3\xba',
              name='staticText1', parent=self.panel1, pos=wx.Point(136, 382),
              size=wx.Size(118, 14), style=0)

        self.staticText2 = wx.StaticText(id=wxID_FRAME1STATICTEXT2,
              label='\xcc\xf5\xc2\xeb\xca\xb6\xb1\xf0\xcd\xbc\xcf\xf1\xb2\xb6\xd7\xbd\xd6\xfa\xca\xd6',
              name='staticText2', parent=self.panel1, pos=wx.Point(384, 16),
              size=wx.Size(200, 23), style=0)
        self.staticText2.SetFont(wx.Font(14, wx.SWISS, wx.NORMAL, wx.BOLD,
              False, 'Tahoma'))

        self.button1 = wx.Button(id=wxID_FRAME1BUTTON1, label='+',
              name='button1', parent=self.panel1, pos=wx.Point(31, 378),
              size=wx.Size(32, 24), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
              id=wxID_FRAME1BUTTON1)

        self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label='-',
              name='button2', parent=self.panel1, pos=wx.Point(76, 378),
              size=wx.Size(32, 24), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
              id=wxID_FRAME1BUTTON2)

        self.textCtrl2 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL2, name='textCtrl2',
              parent=self.panel1, pos=wx.Point(862, 58), size=wx.Size(149, 302),
              style=wx.TE_MULTILINE, value='')

        self.button3 = wx.Button(id=wxID_FRAME1BUTTON3,
              label='\xb5\xbc\xb3\xf6', name='button3', parent=self.panel1,
              pos=wx.Point(880, 379), size=wx.Size(104, 24), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnButton3Button,
              id=wxID_FRAME1BUTTON3)

        self.staticText3 = wx.StaticText(id=wxID_FRAME1STATICTEXT3,
              label='\xcd\xbc\xc6\xac\xc9\xcf\xcf\xde(KB)\xa3\xba',
              name='staticText3', parent=self.panel1, pos=wx.Point(611, 382),
              size=wx.Size(84, 14), style=0)

        self.textCtrl3 = wx.TextCtrl(id=wxID_FRAME1TEXTCTRL3, name='textCtrl3',
              parent=self.panel1, pos=wx.Point(705, 380), size=wx.Size(116, 22),
              style=0, value='50')

        self.staticText5 = wx.StaticText(id=wxID_FRAME1STATICTEXT5,
              label='            -                 ', name='staticText5',
              parent=self.panel1, pos=wx.Point(656, 24), size=wx.Size(336, 14),
              style=wx.ALIGN_RIGHT)

        self.staticText4 = wx.StaticText(id=wxID_FRAME1STATICTEXT4, label='-',
              name='staticText4', parent=self.panel1, pos=wx.Point(447, 381),
              size=wx.Size(4, 14), style=0)

    def __init__(self, parent):
        self._init_ctrls(parent)

        self.zoom = 0
        devnum = wx.GetTextFromUser("\xc7\xeb\xca\xe4\xc8\xeb\xc9\xe3\xcf\xf1\xc9\xe8\xb1\xb8\xb6\xcb\xbf\xda\xba\xc5\xa3\xba", "", "0")

        try:
            self.devnum = int(devnum)
            self.cam = VideoCapture.Device(devnum=self.devnum)
            self.cam_lock = False
            # self.cam.setResolution(800, 600)  
            # self.cam.displayCapturePinProperties()  
            # self.cam.displayCaptureFilterProperties()  
            print 'cam init'
            time.sleep(2)
            im = self.cam.getImage()
            print 'cam start'
            self.timer1.Start(500)
            self.timer2.Start(60000)
        except:
            wx.MessageBox(traceback.format_exc(), "Error!", wx.OK)

        
        

    def OnButton1Button(self, event):
        self.zoom += 0.02
        if self.zoom > 0.4:
            self.zoom = 0.4
        event.Skip()


    def OnButton2Button(self, event):
        self.zoom -= 0.02
        if self.zoom < 0:
            self.zoom = 0            
        event.Skip()


    def OnButton3Button(self, event):
        s = self.textCtrl2.GetValue()

        if not os.path.exists("./output"):
            os.makedirs("./output")

        fnames = []
        for line in s.split("\n"):
            text = line.strip()
            if text:
                fname = text + ".jpg"
                fnames.append(fname)

        print fnames
        stays = fnames[:]

        for root, dirs, files in os.walk("./pics"):
            for fname in files:
                if fname in fnames:
                    from_path = os.path.join(root, fname)
                    to_path = os.path.join("./output", fname)
                    shutil.copy(from_path, to_path)
                    print from_path, to_path
                    stays.remove(fname)

        if stays:
            wx.MessageBox("Can Not Find: " + " , ".join(stays))
        else:
            wx.MessageBox("\xcd\xbc\xc6\xac\xb3\xc9\xb9\xa6\xb5\xbc\xb3\xf6\xd6\xc1 output \xd6\xd0\xa3\xa1")


        event.Skip()


    def OnTextCtrl1TextEnter(self, event):
        text = self.textCtrl1.GetValue()
        text = text.strip().split("\n")[-1].strip()
        self.textCtrl1.SetValue("")
        self.staticText4.SetLabel(text)
        
        if text:
            try:
                dist = datetime.datetime.now().strftime("./pics/%Y/%m/%d/")
                if not os.path.exists(dist):
                    os.makedirs(dist)
                dist = dist + text + ".jpg"
                
                while self.cam_lock:
                    time.sleep(0.1)

                im = self.cam.getImage()
                w,h = im.size
                im = im.crop((int(self.zoom*w), int(self.zoom*h), int(w-(self.zoom*w)), int(h-(self.zoom*h))))
                im.save(dist)
                max_size = int(self.textCtrl3.GetValue()) * 1000
                while True:
                    size = os.path.getsize(dist)
                    if size < max_size:
                        break
                    w,h = im.size
                    w = int(w*0.6)
                    h = int(h*0.6)
                    if w < 200 or h < 200:
                        break
                    im = im.resize((w, h), 1)
                    im.save(dist)
                w,h = self.staticBitmap2.GetSize()
                pic = wx.Image(dist)
                bmp = pic.Rescale(w,h).ConvertToBitmap()
                self.staticBitmap2.SetBitmap(bmp)
                del im
                del pic
                del bmp
            except:
                wx.MessageBox(traceback.format_exc(), "Error!", wx.OK)
                
        event.Skip()


    def OnTimer1Timer(self, event):

        self.timer1.Stop()
        
        try:
            im = self.cam.getImage()
            w,h = im.size
            im = im.crop((int(self.zoom*w), int(self.zoom*h), int(w-(self.zoom*w)), int(h-(self.zoom*h))))
            im.save('image.jpg')
            w,h = self.staticBitmap1.GetSize()
            pic = wx.Image('image.jpg')
            bmp = pic.Rescale(w,h).ConvertToBitmap()
            self.staticBitmap1.SetBitmap(bmp)
            del im
            del pic
            del bmp
        except:
            wx.MessageBox(traceback.format_exc(), "Error!", wx.OK)
            
        self.timer1.Start(500)
        
        event.Skip()


    def OnTimer2Timer(self, event):
        pass
        # try:
        #     self.cam_lock = True

        #     del self.cam
        #     self.cam = VideoCapture.Device(devnum=self.devnum)
        #     print 'cam init'
        #     time.sleep(0.1)
        #     im = self.cam.getImage()
        #     print 'cam start'

        #     del self.staticBitmap1
        #     del self.staticBitmap2

        #     self.staticBitmap1 = wx.StaticBitmap(bitmap=wx.NullBitmap,
        #           id=wxID_FRAME1STATICBITMAP1, name='staticBitmap1',
        #           parent=self.panel1, pos=wx.Point(19, 59), size=wx.Size(400, 300),
        #           style=0)

        #     self.staticBitmap2 = wx.StaticBitmap(bitmap=wx.NullBitmap,
        #           id=wxID_FRAME1STATICBITMAP2, name='staticBitmap2',
        #           parent=self.panel1, pos=wx.Point(441, 59), size=wx.Size(400, 300),
        #           style=0)

        #     self.cam_lock = False

        # except:
        #     wx.MessageBox(traceback.format_exc(), "Error!", wx.OK)
        #     self.cam_lock = False        
        
